<template>
  <div class="division-statistics">
    <el-card class="page-container">
      <template #header>
        <div class="card-header">
          <span>按行政区域统计</span>
          <el-button type="success" @click="exportExcel" class="export-btn">导出统计结果</el-button>
        </div>
      </template>
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="行政区域">
          <el-cascader
            v-model="searchForm.division"
            :options="divisionOptions"
            :props="{ checkStrictly: true, emitPath: false, value: 'code', label: 'name', children: 'children' }"
            placeholder="请选择行政区域"
            clearable
            filterable
            style="width: 300px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 统计表格 -->
      <el-table :data="filteredData" border style="width: 100%; margin-bottom: 30px;">
        <el-table-column prop="code" label="区域编码" min-width="120" />
        <el-table-column prop="name" label="区域名称" min-width="120" />
        <el-table-column prop="level" label="级别" min-width="80" />
        <el-table-column prop="population" label="参保人数" min-width="100" />
        <el-table-column prop="totalAmount" label="报销总金额（元）" min-width="150" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 梧州多级行政区域信息（县-镇-村-组，部分示例数据）
const divisionOptions = [
  {
    code: '450421', name: '苍梧县', level: 1, children: [
      {
        code: '45042101', name: '龙圩镇', level: 2, children: [
          {
            code: '4504210101', name: '龙圩镇恩义村', level: 3 },
          {
            code: '4504210102', name: '龙圩镇新村', level: 3 }
        ]
      },
      {
        code: '45042102', name: '沙头镇', level: 2, children: [
          {
            code: '4504210201', name: '沙头镇大村', level: 3 }
        ]
      }
    ]
  },
  {
    code: '450422', name: '藤县', level: 1, children: [
      {
        code: '45042201', name: '藤州镇', level: 2, children: [
          {
            code: '4504220101', name: '藤州镇新村', level: 3 }
        ]
      }
    ]
  },
  {
    code: '450403', name: '万秀区', level: 1, children: [
      {
        code: '45040301', name: '城东街道', level: 2, children: [
          {
            code: '4504030101', name: '城东社区', level: 3 }
        ]
      }
    ]
  }
]

// 扁平化所有区域用于表格和导出
function flattenDivisions(options) {
  const result = []
  function dfs(list) {
    for (const item of list) {
      result.push(item)
      if (item.children) dfs(item.children)
    }
  }
  dfs(options)
  return result
}
const allData = ref(flattenDivisions(divisionOptions).map(item => ({
  ...item,
  population: Math.floor(Math.random() * 10000 + 100),
  totalAmount: Math.floor(Math.random() * 1000000 + 10000)
})))

// 筛选表单
const searchForm = reactive({
  division: ''
})

// 过滤后的数据
const filteredData = computed(() => {
  if (!searchForm.division) return allData.value
  return allData.value.filter(item => item.code === searchForm.division)
})

// 查询
const handleSearch = () => {
  ElMessage.success('筛选成功')
}
const resetSearch = () => {
  searchForm.division = ''
}

// 导出功能
const exportExcel = () => {
  const header = ['区域编码', '区域名称', '级别', '参保人数', '报销总金额（元）']
  const rows = filteredData.value.map(item => [item.code, item.name, item.level, item.population, item.totalAmount])
  let csvContent = '\uFEFF' + header.join(',') + '\n' + rows.map(e => e.join(',')).join('\n')
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `按行政区域统计.csv`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('导出成功')
}
</script>

<style scoped>
.division-statistics {
  padding: 20px;
}
.page-container {
  min-height: calc(100vh - 140px);
}
.card-header {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-form {
  margin-bottom: 20px;
}
.export-btn {
  margin-left: auto;
}
</style>